import * as XLSX from "xlsx";

export default {
    loadData(file){
        return new Promise((resolve, reject)=>{
            const reader = new FileReader();
            reader.onload = (e) => {
                const data = e.target.result;
                const workbook = XLSX.read(data, { type: "binary" });
                let resMap = {}
                workbook.SheetNames.forEach((sheetName)=>{
                    const worksheet = workbook.Sheets[sheetName];
                    resMap[sheetName] = XLSX.utils.sheet_to_json(worksheet, { header: 1 });//二维数组
                })
                resolve(resMap)
            };
            reader.readAsBinaryString(file);
        })
    },
    load(columns,file){
       return this.loadData(file).then(map=>{
            return this.loadV2(columns , map)
        })
    },
    /**
     *
     * @param columns {[{key: ''}]}
     * @param mapData {{key: [[]]}}
     */
    loadV2(columns,mapData){
        let resMap = {}
        for(let s in mapData){
            resMap[s] = this.loadByJsonData(columns , mapData[s]) ;
        }
        return resMap
    },
    /*jsonData 要是二维数组*/
    loadByJsonData(columns,jsonData){
        let res = []
        for(let i = 0 ;i< jsonData.length ;i++){
            let items = jsonData[i] ;
            let temp = {} ;
            columns.forEach((item,index)=>{
                let i = item.index || index
                temp[item.key] = items[i]
            })
            res.push(temp)
        }
        return res
    }
}